import os, time

# 设置VLC库路径，需在import vlc之前
# os.environ['PYTHON_VLC_MODULE_PATH'] = "./vlc-3.0.6"

import vlc
import platform


class Player:
    '''
        args:设置 options
    '''
    def __init__(self, *args):
        # if args:
        #     self.instance = vlc.Instance(*args) 
        #     self.player = self.instance.media_player_new()
        #     self.media = self.instance.media_new()
        # else:

        self.os_type = "Windows"

        self.mrl = None

        self.instance = vlc.Instance("--no-xlib --live-caching=300 --vout=gl")
        self.player = self.instance.media_player_new()
        self.media = None
            
        self.record_player = self.instance.media_player_new() 
        self.record_media = None
        self.record_path = None

    # 设置待播放的url地址或本地文件路径，每次调用都会重新加载资源
    def set_uri(self, uri):
        self.mrl = uri
        
    # 播放 成功返回0，失败返回-1
    def play(self, path=None):

        if (path is not None) and (path != self.mrl):
            self.set_uri(path)
            if self.media is not None:
                self.media.release()
                self.media = None
        
        if self.mrl is None:
            return -1
        
        if self.media is None:
            self.media = self.instance.media_new(self.mrl)
            # self.media.add_option(":sout=#display")           # 仅显示画面
            self.player.set_media(self.media) 
        
        return self.player.play()
        
    def take_screenshot(self, path):
        self.player.video_take_snapshot(0, path, 0, 0)

    def start_recording(self, path, caching=2000):
        
        if self.record_media is not None:
            return  
        
        self.record_path = path
        # 这里需要根据 VLC 具体 API 来设置录制参数
        # 简单示例，假设可以通过设置输出路径来实现录制
        # self.media.add_option(f":sout=#file{{dst={path}}}")
        # self.media.add_option(":sout-keep")
        # self.player.play()

        # sout_options = f'#transcode{{vcodec=h264,acodec=mpga,ab=128,channels=2,samplerate=44100}}:file{{dst={path}}}'
        # instance = vlc.Instance(f'--sout={sout_options}')
        # record_media = instance.media_new(self.player.get_media().get_mrl())
        # record_player = instance.media_player_new()
        # record_player.set_media(record_media)
        # self.record_player = record_player
        # self.record_player.play()

        # self.player.get_media().add_options(f":sout=#file{{dst={path}}}")
         
        # instance = vlc.Instance("--no-xlib")
        # self.record_player = self.instance.media_player_new()


        # 配置输出
        # record_media = self.instance.media_new(self.player.get_media().get_mrl())
        # sout = f":sout=#transcode{{vcodec=h264}}:std{{access=file,mux=mp4,dst={self.record_path}}}"
        # record_media.add_option(sout)
        # record_media.add_option(f":sout-mux-caching={caching}")
        # self.media.add_option(":sout-keep")

        # self.record_player.set_media(record_media)

        
        self.record_player = self.instance.media_player_new()
        self.record_media = self.instance.media_new(self.mrl)
        # 配置编码参数（使用硬件加速）
        # sout = (
        #     ":sout=#transcode{"
        #         "vcodec=h264_nvenc,"  # NVIDIA 硬件编码（或 h264_vaapi 用于 Intel GPU）
        #         "acodec=none,"         # 不录制音频
        #         "fps=30," 
        #         "width=1280,height=720"
        #     "}:std{access=file,mux=mp4,dst={self.record_path}}"
        # )
        
        sout = f":sout=#transcode{{vcodec=h264_nvenc,acodec=none}}:std{{access=file,mux=mp4,dst={self.record_path}}}"
        self.record_media.add_option(sout) 
        self.record_player.set_media(self.record_media)

        self.record_player.play()
        print("录制开始...")


    def stop_recording(self):
        if self.record_player is not None:
            # 停止录制逻辑
            self.record_player.stop() 
            
        if self.record_media is not None: 
            self.record_media.release()
            self.record_media = None

        print("录制结束.")


    # 暂停
    def pause(self):
        self.player.pause()

    # 恢复
    def resume(self):
        self.player.set_pause(0)

    # 停止
    def stop(self):
        self.player.stop()

    # 释放资源
    def release(self):
        return self.player.release()

    # 是否正在播放
    def is_playing(self):
        return self.player.is_playing()

    # 已播放时间，返回毫秒值
    def get_time(self):
        return self.player.get_time()

    # 拖动指定的毫秒值处播放。成功返回0，失败返回-1 (需要注意，只有当前多媒体格式或流媒体协议支持才会生效)
    def set_time(self, ms):
        return self.player.get_time()

    # 音视频总长度，返回毫秒值
    def get_length(self):
        return self.player.get_length()

    # 获取当前音量（0~100）
    def get_volume(self):
        return self.player.audio_get_volume()

    # 设置音量（0~100）
    def set_volume(self, volume):
        return self.player.audio_set_volume(volume)

    # 返回当前状态：正在播放；暂停中；其他
    def get_state(self):
        state = self.player.get_state()
        if state == vlc.State.Playing:
            return 1
        elif state == vlc.State.Paused:
            return 0
        else:
            return -1

    # 当前播放进度情况。返回0.0~1.0之间的浮点数
    def get_position(self):
        return self.player.get_position()

    # 拖动当前进度，传入0.0~1.0之间的浮点数(需要注意，只有当前多媒体格式或流媒体协议支持才会生效)
    def set_position(self, float_val):
        return self.player.set_position(float_val)

    # 获取当前文件播放速率
    def get_rate(self):
        return self.player.get_rate()

    # 设置播放速率（如：1.2，表示加速1.2倍播放）
    def set_rate(self, rate):
        return self.player.set_rate(rate)

    # 设置宽高比率（如"16:9","4:3"）
    def set_ratio(self, ratio):
        self.player.video_set_scale(0)  # 必须设置为0，否则无法修改屏幕宽高
        self.player.video_set_aspect_ratio(ratio)

    # 注册监听器
    def add_callback(self, event_type, callback):
        self.player.event_manager().event_attach(event_type, callback)

    # 移除监听器
    def remove_callback(self, event_type, callback):
        self.player.event_manager().event_detach(event_type, callback)

    def set_marquee(self):
        self.player.video_set_marquee_int(vlc.VideoMarqueeOption.Enable, 1)
        self.player.video_set_marquee_int(vlc.VideoMarqueeOption.Size, 28)
        self.player.video_set_marquee_int(vlc.VideoMarqueeOption.Color, 0xffff00)  # 黄色
        # 将 vlc.Position.top 替换为对应的整数值 7
        self.player.video_set_marquee_int(vlc.VideoMarqueeOption.Position, 7)
        self.player.video_set_marquee_int(vlc.VideoMarqueeOption.Timeout, 0)
        self.player.video_set_marquee_int(vlc.VideoMarqueeOption.Refresh, 1000)

    def update_text(self, content):
        self.player.video_set_marquee_string(vlc.VideoMarqueeOption.Text, content)

    def set_window(self, canvas_id): 
        """将 VLC 视频绑定到 Tkinter Canvas""" 
        self.os_type = platform.system()
        if self.os_type == "Windows":
            self.player.set_hwnd(canvas_id)
        elif self.os_type == "Linux":
            self.player.set_xwindow(canvas_id)

def my_call_back(event):
    # print("call:", player.get_time())
    pass


if "__main__" == __name__:
    player = Player()
    player.add_callback(vlc.EventType.MediaPlayerTimeChanged, my_call_back)
    # 在线播放流媒体视频
    player.play("rtsp://192.168.0.123:554/live/mainstream")
    
    player.set_marquee()
    player.update_text("%Y-%m-%d %H:%M:%S")

    # 播放本地mp3
    # player.play("D:/abc.mp3")

    # 防止当前进程退出
    while True:
        pass
